package com.zhongkai.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.mysql.jdbc.StringUtils;
import com.zhongkai.Bean.PageBean;
import com.zhongkai.Bean.WebSocketIndBean;
import com.zhongkai.MessageTool;
import com.zhongkai.app.service.IBaseDao;
import com.zhongkai.app.service.IndentStorageService;
import com.zhongkai.app.service.PageQuerDao;
import com.zhongkai.listener.RocketMqProducer;
import com.zhongkai.model.utils.TTHelp;
import com.zhongkai.model.utils.ZhongkaiResult;
import com.zhongkai.model3.*;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.regex.Pattern;

/**
 * 采购入库
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class IndentStorageServiceImpl implements IndentStorageService {

    @Autowired
    private IBaseDao iBaseDao;

    @Autowired
    private PageQuerDao pageQuerDao;


/*    @Autowired
    private JmsTemplate jmsTemplate;

    @Resource
    private Destination topicDestination;*/

    @Autowired
    private RocketMqProducer rocketMqProducer;

    /**
     * 采购入库
     *
     * @param id       采购订单id
     * @param ind_put  入库人员name
     * @param put_uuid 入库人员uuid
     */
    @Override
    public ZhongkaiResult putStorage(Long id, String ind_put, String put_uuid) {

        if (id == 0 || StringUtils.isNullOrEmpty(ind_put) || StringUtils.isNullOrEmpty(put_uuid)) {
            return ZhongkaiResult.build(400, "数据不完整");
        }

        final Indent indent = (Indent) iBaseDao.get("from Indent ind where ind.id='" + id + "'");

        Warehouse warehouse = (Warehouse) iBaseDao.get("from Warehouse wa where wa.warName='" + indent.getIndName() + "'");


        if (indent == null) {
            return ZhongkaiResult.build(400, "此订单不存在");
        } else if ("2".equals(indent.getIsPut())) {
            return ZhongkaiResult.build(400, "此订单已入库");
        }

        boolean integer = isInteger(indent.getIndCount());

        if (!integer) {
            return ZhongkaiResult.build(400, "订单商品数量须为整数");
        }


        indent.setIndPut(ind_put);
        indent.setPutUuid(put_uuid);
        long millis = new DateTime().getMillis(); //获取当前系统时间戳
        indent.setPutTime(millis);//入库时间
        indent.setIsPut("2");//1未入库 2入库

        //.........................


        int count = Integer.parseInt(indent.getIndCount());
        String m_uuid;
        //Warehouse warehouse = new Warehouse();//库存表
        if (warehouse == null) {
            String uuid = TTHelp.generate();
            m_uuid = uuid;
            warehouse = new Warehouse();
            warehouse.setWarUuid(uuid);
            warehouse.setWarName(indent.getIndName());


            warehouse.setWarCount(count);

            iBaseDao.save(warehouse);

        } else { //库存中有此商品

            m_uuid = warehouse.getWarUuid();
            Integer warCount = warehouse.getWarCount() + count;
            warehouse.setWarCount(warCount);
            iBaseDao.update(warehouse);
        }

        Record record = new Record(); //库存操作记录表
        //record.
        record.setWarUuid(m_uuid);
        record.setWarName(warehouse.getWarName());
        record.setIndUuid(indent.getIndUuid()); //订单编号
        record.setWarCount(indent.getIndCount());//操作数量
        record.setRecordUser(ind_put);//入库人员姓名
        record.setUserId(put_uuid);//入库人员姓名
        record.setRecordTime(millis);//时间
        record.setRecordType("1"); //1入库 2出库
        try {

            iBaseDao.save(record); //入库记录单
            iBaseDao.update(indent);

            String dateTime = new DateTime(indent.getIndTime()).toString("yyyy-MM-dd HH:mm:ss");

            WebSocketIndBean indBean = new WebSocketIndBean();
            indBean.setUser_uuid(indent.getPersonUuid());
            indBean.setType("3");
            indBean.setContent("您于 " + dateTime + " 提交的" + indent.getIndName() + "采购申请,已入库");

            ObjectMapper mapper = new ObjectMapper();


            String json = MessageTool.FWEB_DATE + mapper.writeValueAsString(indBean);

            byte[] bytes = json.getBytes("utf-8");

            rocketMqProducer.sendMsgIntime(MessageTool.BIG_SKY, MessageTool.FWEB_DATE, bytes);




/*
            jmsTemplate.send(topicDestination, new MessageCreator() {
                @Override
                public Message createMessage(Session session) throws JMSException {

                    TextMessage textMessage = session.createTextMessage(json);
                    return textMessage;
                }
            });*/
            return ZhongkaiResult.ok();
        } catch (Exception e) {
            e.printStackTrace();
            return ZhongkaiResult.build(400, "入库失败");
        }
    }

    @Override
    public ZhongkaiResult listStorage(Integer page, Integer rows) { //已审批列表
        if (page == 0 || rows == 0) {
            return ZhongkaiResult.build(400, "数据不完整");
        }


        PageBean pageBean = new PageBean();
        pageBean.setCurrentPage(page);
        pageBean.setPageSize(rows);
        DetachedCriteria detachedCriteria = DetachedCriteria.forClass(Indent.class);
        detachedCriteria.add(Restrictions.eq("indRemove", "1")); //增加条件
        detachedCriteria.add(Restrictions.eq("indState", 2)); //已审批列表
        detachedCriteria.addOrder(Order.desc("indTime")); //根据传入的字段进行降序排序
        pageBean.setDetachedCriteria(detachedCriteria);
        pageQuerDao.pageQuery(pageBean);
        return ZhongkaiResult.ok(pageBean);

    }

    //---------------------------------------办公入库--------------------------------------------------------------------

    /**
     * 采购入库
     *
     * @param id       采购订单id
     * @param ind_put  入库人员name
     * @param put_uuid 入库人员uuid
     */
    @Override
    public ZhongkaiResult putStorage2(Long id, String ind_put, String put_uuid) {

        if (id == 0 || StringUtils.isNullOrEmpty(ind_put) || StringUtils.isNullOrEmpty(put_uuid)) {
            return ZhongkaiResult.build(400, "数据不完整");
        }

        final Indent2 indent = (Indent2) iBaseDao.get("from Indent2 ind where ind.id='" + id + "'");

        if (indent == null) {
            return ZhongkaiResult.build(400, "此订单不存在");
        } else if ("2".equals(indent.getIsPut())) {
            return ZhongkaiResult.build(400, "此订单已入库");
        }

        boolean integer = isInteger(indent.getIndCount());

        if (!integer) {
            return ZhongkaiResult.build(400, "订单商品数量须为整数");
        }

        indent.setIndPut(ind_put);
        indent.setPutUuid(put_uuid);
        long millis = new DateTime().getMillis(); //获取当前系统时间戳
        indent.setPutTime(millis);//入库时间
        indent.setIsPut("2");//1未入库 2入库

        //.........................
        Warehouse2 warehouse = (Warehouse2) iBaseDao.get("from Warehouse2 wa where wa.warName='" + indent.getIndName() + "'");
        int count = Integer.parseInt(indent.getIndCount());
        String m_uuid;
        //Warehouse warehouse = new Warehouse();//库存表
        if (warehouse == null) {
            String uuid = TTHelp.generate();
            m_uuid = uuid;
            warehouse = new Warehouse2();
            warehouse.setWarUuid(uuid);
            warehouse.setWarName(indent.getIndName());


            warehouse.setWarCount(count);

            iBaseDao.save(warehouse);

        } else { //库存中有此商品

            m_uuid = warehouse.getWarUuid();
            Integer warCount = warehouse.getWarCount() + count;
            warehouse.setWarCount(warCount);
            iBaseDao.update(warehouse);
        }

        Record2 record = new Record2(); //库存操作记录表
        //record.
        record.setWarUuid(m_uuid);
        record.setWarName(warehouse.getWarName());
        record.setIndUuid(indent.getIndUuid()); //订单编号
        record.setWarCount(indent.getIndCount());//操作数量
        record.setRecordUser(ind_put);//入库人员姓名
        record.setUserId(put_uuid);//入库人员姓名
        record.setRecordTime(millis);//时间
        record.setRecordType("1"); //1入库 2出库
        try {

            iBaseDao.save(record); //入库记录单
            iBaseDao.update(indent);
            String dateTime = new DateTime(indent.getIndTime()).toString("yyyy-MM-dd HH:mm:ss");

            WebSocketIndBean indBean = new WebSocketIndBean();
            indBean.setUser_uuid(indent.getPersonUuid());
            indBean.setType("3");
            indBean.setContent("您于 " + dateTime + " 提交的" + indent.getIndName() + "采购申请,已入库");

            ObjectMapper mapper = new ObjectMapper();

            String json = MessageTool.FWEB_DATE + mapper.writeValueAsString(indBean);
            byte[] bytes = json.getBytes("utf-8");

            rocketMqProducer.sendMsgIntime(MessageTool.BIG_SKY, MessageTool.FWEB_DATE, bytes);


 /*           jmsTemplate.send(topicDestination, new MessageCreator() {
                @Override
                public Message createMessage(Session session) throws JMSException {


                    TextMessage textMessage = session.createTextMessage(json);
                    return textMessage;
                }
            });*/

            return ZhongkaiResult.ok();
        } catch (Exception e) {
            e.printStackTrace();
            return ZhongkaiResult.build(400, "入库失败");
        }
    }

    @Override
    public ZhongkaiResult listStorage2(Integer page, Integer rows) { //已审批列表
        if (page == 0 || rows == 0) {
            return ZhongkaiResult.build(400, "数据不完整");
        }


        try {
            PageBean pageBean = new PageBean();
            pageBean.setCurrentPage(page);
            pageBean.setPageSize(rows);
            DetachedCriteria detachedCriteria = DetachedCriteria.forClass(Indent2.class);
            detachedCriteria.add(Restrictions.eq("indRemove", "1")); //增加条件
            detachedCriteria.add(Restrictions.eq("indState", 2)); //已审批列表
            detachedCriteria.addOrder(Order.desc("indTime")); //根据传入的字段进行降序排序
            pageBean.setDetachedCriteria(detachedCriteria);
            pageQuerDao.pageQuery(pageBean);
            return ZhongkaiResult.ok(pageBean);
        } catch (Exception e) {
            e.printStackTrace();
            return ZhongkaiResult.build(405, "查询失败");
        }
    }


    /*方法二：推荐，速度最快
     * 判断是否为整数
     * @param str 传入的字符串
     * @return 是整数返回true,否则返回false
     */

    public boolean isInteger(String str) {
        Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
        return pattern.matcher(str).matches();
    }
}
